import asyncio
import json
import httpx
from loguru import logger

from app.config.settings import CONFIG

server_config = CONFIG["server"]
manager_service = CONFIG["alg"]["manager_service"]

ip = server_config["ip"]
port = server_config["port"]
_id = server_config["unique_id"]
alg_type = server_config["alg_type"]


async def req(client, i):
    data = {"ip": ip, "port": port, "alg_type": alg_type, "id": _id}
    json_data = json.dumps(data)
    logger.info(f'{manager_service}')
    res = await client.post(manager_service, content=json_data)
    print(f"第{i + 1}次请求,status_code = {res.status_code}")
    return res


async def main():
    async with httpx.AsyncClient() as client:
        task_list = []  # 任务列表
        for i in range(3):
            res = req(client, i)
            task = asyncio.create_task(res)  # 创建任务
            task_list.append(task)
        await asyncio.gather(*task_list)  # 收集任务


# asyncio.run(main())

# if __name__ == '__main__':
#     start = time.time()
#     asyncio.run(main())
#     end = time.time()
#     print(f'异步发送3次请求，耗时：{end - start}')
